var stockGroupDAO = require('../controller/controller.stockGroup');
var stockChannelDAO = require('../controller/controller.stockChannel');
var stockDealDAO = require('../controller/controller.stockDeal');
var stockHistoryPriceDAO = require('../controller/controller.stockHistoryPrice');
var stockPositionDAO = require('../controller/controller.stockPosition');
var stockGroupRateDAO = require('../controller/controller.stockGroupRate');

var stockGroupUtil = require('../utils/stockGroup');

var stockUtil = require('../utils/stock');
var timeUtil = require('../utils/timeUtil');
var async = require('async');
/**
 * 股票分组Service
 */
module.exports = {
    getList: function (req, res, next) {
        var params = {};
        var that = this;
        // if (req.session.userinfo && req.session.userinfo.role == 0)
        //     params.createUid = req.session.uid;
        async.waterfall([
            function (done) {//按人查分组
                stockGroupDAO.list(params, function (err, result) {
                    if (err) {
                        next({'code': 404, 'message': "查询分组错误"});
                        return;
                    }
                    var list = [];
                    if (result && result.obj) {
                        list = result.obj;
                    }
                    done(err, list);
                });
            },
            function (stockGroups, done) {//按股票查询实价
                async.each(stockGroups, function (stockGroup, callback) {
                    var stockCodes = [];
                    // async.waterfall([
                    //     function (cb) {
                    stockChannelDAO.getByGroupId({stockGroupId: stockGroup.rowId}, function (err, res) {
                        stockGroup.stockChannelIds = res.obj;
                        for (stockChannel of res.obj) {
                            stockCodes.push(stockChannel.stockId.stockCode);

                        }
                        if (stockCodes.length == 0) {
                            callback();
                        } else {
                            stockUtil.getRealtimeListPrice(stockCodes, function (err, res) {
                                var i = 0;
                                for (stockChannel of stockGroup.stockChannelIds) {
                                    stockChannel.stockId.realPrice = res[i];
                                    i++;
                                }
                                callback();
                            });
                        }
                    });

                }, function (err) {
                    done(err, stockGroups);
                });
            },
            function (stockGroups, done) {//按股票查询各区间价格做收益率统计

                async.each(stockGroups, function (stockGroup, call) {
                    var stockCodes = [];
                    var stockChannelIds = [];
                    var realPics = [];
                    for (stockChannel of stockGroup.stockChannelIds) {
                        var stockCode = stockChannel.stockId.stockCode;
                        stockCodes.push(stockCode.substr(0, stockCode.indexOf(".")));
                        stockChannelIds.push(stockChannel.rowId);
                        realPics.push(stockChannel.stockId.realPrice);
                    }
                    var day = new Date();
                    var startDate = "";
                    var endDate = "";
                    async.parallel({
                        ljInfos: function (cb) {
                            // stockChannelDAO.getByGroupId({stockGroupId: stockGroup && stockGroup.rowId || null}, function (err, res) {
                            //     cb(err, res.obj);
                            // });
                            cb(null, stockGroup.stockChannelIds);
                        },
                        yearInfos: function (cb) {
                            startDate = day.getFullYear() + "-01-01";
                            endDate = day.getFullYear() + "-" + (day.getMonth() + 1) + "-" + (day.getDate() + 1);
                            if (stockCodes.length == 0) {
                                cb(null, []);
                            } else {
                                async.parallel({
                                    startDeals: function (ca) {//年前量
                                        stockDealDAO.getAllInDate({
                                            stockChannelIds: stockGroup && stockGroup.stockChannelIds || [],
                                            endDate: startDate
                                        }, function (err, res) {
                                            ca(err, res.obj);
                                        });
                                    },
                                    endDeals: function (ca) {//年后量
                                        stockDealDAO.getAllInDate({
                                            stockChannelIds: stockGroup && stockGroup.stockChannelIds || [],
                                            startDate: startDate,
                                            endDate: endDate
                                        }, function (err, res) {
                                            ca(err, res.obj);
                                        });
                                    },
                                    firstPrice: function (ca) {//年前最后天价格
                                        stockHistoryPriceDAO.getListPriceByTime({
                                            date: startDate,
                                            stockCodes: stockCodes
                                        }, function (err, result) {
                                            if (err) {
                                                console.log(err);
                                            } else {
                                                ca(null, result.obj);
                                            }
                                        });
                                    }
                                }, function (err, res) {
                                    cb(err, res);
                                });
                            }
                        },
                        dayInfos: function (cb) {
                            startDate = day.getFullYear() + "-" + (day.getMonth() + 1) + "-" + day.getDate();
                            endDate = day.getFullYear() + "-" + (day.getMonth() + 1) + "-" + (day.getDate() + 1);
                            if (stockCodes.length == 0) {
                                cb(null, []);
                            } else {
                                async.parallel({
                                    startDeals: function (ca) {//昨天量
                                        stockDealDAO.getAllInDate({
                                            stockChannelIds: stockGroup && stockGroup.stockChannelIds || [],
                                            endDate: startDate
                                        }, function (err, res) {
                                            ca(err, res.obj);
                                        });
                                    },
                                    endDeals: function (ca) {//今天量
                                        stockDealDAO.getAllInDate({
                                            stockChannelIds: stockGroup && stockGroup.stockChannelIds || [],
                                            startDate: startDate,
                                            endDate: endDate
                                        }, function (err, res) {
                                            ca(err, res.obj);
                                        });
                                    },
                                    firstPrice: function (ca) {//昨天价格
                                        stockHistoryPriceDAO.getListPriceByTime({
                                            date: startDate,
                                            stockCodes: stockCodes
                                        }, function (err, result) {
                                            if (err) {
                                                console.log(err);
                                            } else {
                                                ca(null, result.obj);
                                            }
                                        });
                                    }
                                }, function (err, res) {
                                    cb(err, res);
                                });
                            }
                        },
                        }, function (err, result) {
                        var nums = [];
                        for (stockChannel of result.ljInfos) {
                            nums.push(stockChannel.positionNum)
                        }
                        let realPrices = 0;
                        async.parallel({
                            ljListRalt: function (cb) {
                                let ljPrices = 0;
                                let i = 0;
                                for (stockChannel of result.ljInfos) {
                                    ljPrices += (stockChannel.cost || 0) * stockChannel.positionNum;
                                    realPrices += (realPics[i] || 0) * stockChannel.positionNum;
                                    i++;
                                }

                                cb(err, stockUtil.calcRate(realPrices, ljPrices));
                            },
                            yearListRalt: function (cb) {
                                that.countRate(result.yearInfos, stockGroup, cb);
                            },
                            dayListRalt: function (cb) {
                                that.countRate(result.dayInfos, stockGroup, cb);
                            },
                            }, function (err, res) {
                                stockGroup.ljRate = res.ljListRalt;
                                stockGroup.yearRate = res.yearListRalt;
                                stockGroup.dayRate = res.dayListRalt;
                                call(null, stockGroup)
                            })

                        }
                    )

                }, function (err) {
                    done(err, stockGroups);
                })

            }
        ], function (error, result) {
            if (error) {
                console.log(error);
                next({code: 404, message: '股票分组查询出错'})
            } else {
                next({code: 200, result});
            }
        });
    },
    countRalt: function (oldPrice, realPrice) {
        var rate = oldPrice== 0 ?0:((realPrice - oldPrice) * 100 / oldPrice);
        return rate.toFixed(2) + '%';
    },
    getByGroupId: function (req, res, next) {
        var stockCodes = [];
        var that = this;
        if(!req.body.params.groupId)
            next({'code': 404, 'message': "分组信息错误"})
        async.waterfall([
            function (done) {//查询分组信息
                stockGroupUtil.getGroupRealVal(req.body.params.groupId,function(err,result){
                //stockGroupDAO.get({rowId: req.body.params.groupId || ''}, function (err, result) {
                    if (err || !result) {
                        done({'code': 404, 'message': "查询分组信息错误"});
                    }
                    done(null, result);
                });
            },
            function (stockGroup, done) {//查询组合收益率
                stockGroupRateDAO.list({stockGroupId:stockGroup.rowId},function(err,result){
                    if (err) {
                        done({'code': 404, 'message': "查询组合收益率错误"});
                    }
                    stockGroup.stockGroupRates = result.obj;
                    done(null, stockGroup);
                })
            },
            function (stockGroup, done) {//按股票查询实价
                async.waterfall([
                    function (cb) {
                        stockChannelDAO.getByGroupId({stockGroupId: stockGroup && stockGroup.rowId || null}, function (err, res) {
                            stockGroup.stockChannelIds = res.obj;
                            for (stockChannel of res.obj) {
                                stockCodes.push(stockChannel.stockId.stockCode);
                            }
                            cb(err, stockCodes);
                        });
                    },
                    function (stockCodes, cb) {
                        if (stockCodes.length == 0) {
                            cb(null, stockGroup);
                        } else {
                            stockUtil.getRealtimeListPrice(stockCodes, function (err, res) {
                                var i = 0;
                                for (stockChannel of stockGroup.stockChannelIds) {
                                    stockChannel.stockId.realPrice = res[i];
                                    i++;
                                }
                                cb(err, stockGroup);
                            });
                        }
                    }
                ], function (err, res) {
                    done(err, res);
                });
            },
            function (stockGroup, done) {//按股票查询各区间价格做收益率统计

                var stockChannelIds = [];

                var realPics = [];
                stockCodes = [];
                for (stockChannel of stockGroup.stockChannelIds) {
                    var stockCode = stockChannel.stockId.stockCode;
                    stockCodes.push(stockCode.substr(0, stockCode.indexOf(".")));
                    stockChannelIds.push(stockChannel.rowId);
                    realPics.push(stockChannel.stockId.realPrice);
                }
                var day = new Date();
                var startDate = "";
                var endDate = "";
                async.parallel({
                        ljInfos: function (cb) {
                            // stockChannelDAO.getByGroupId({stockGroupId: stockGroup && stockGroup.rowId || null}, function (err, res) {
                            //     cb(err, res.obj);
                            // });
                            cb(null, stockGroup.stockChannelIds);
                        },
                        yearInfos: function (cb) {
                            startDate = day.getFullYear() + "-01-01";
                            endDate = day.getFullYear() + "-" + (day.getMonth() + 1) + "-" + (day.getDate() + 1);
                            if (stockCodes.length == 0) {
                                cb(null, []);
                            } else {
                                async.parallel({
                                    startDeals: function (ca) {//年前量
                                        stockDealDAO.getAllInDate({
                                            stockChannelIds: stockGroup && stockGroup.stockChannelIds || [],
                                            endDate: startDate
                                        }, function (err, res) {
                                            ca(err, res.obj);
                                        });
                                    },
                                    endDeals: function (ca) {//年后量
                                        stockDealDAO.getAllInDate({
                                            stockChannelIds: stockGroup && stockGroup.stockChannelIds || [],
                                            startDate: startDate,
                                            endDate: endDate
                                        }, function (err, res) {
                                            ca(err, res.obj);
                                        });
                                    },
                                    firstPrice: function (ca) {//年前最后天价格
                                        stockHistoryPriceDAO.getListPriceByTime({
                                            date: startDate,
                                            stockCodes: stockCodes
                                        }, function (err, result) {
                                            if (err) {
                                                console.log(err);
                                            } else {
                                                ca(null, result.obj);
                                            }
                                        });
                                    }
                                }, function (err, res) {
                                    cb(err, res);
                                });
                            }
                        },
                        dayInfos: function (cb) {
                            startDate = day.getFullYear() + "-" + (day.getMonth() + 1) + "-" + day.getDate();
                            endDate = day.getFullYear() + "-" + (day.getMonth() + 1) + "-" + (day.getDate() + 1);
                            if (stockCodes.length == 0) {
                                cb(null, []);
                            } else {
                                async.parallel({
                                    startDeals: function (ca) {//昨天量
                                        stockDealDAO.getAllInDate({
                                            stockChannelIds: stockGroup && stockGroup.stockChannelIds || [],
                                            endDate: startDate
                                        }, function (err, res) {
                                            ca(err, res.obj);
                                        });
                                    },
                                    endDeals: function (ca) {//今天量
                                        stockDealDAO.getAllInDate({
                                            stockChannelIds: stockGroup && stockGroup.stockChannelIds || [],
                                            startDate: startDate,
                                            endDate: endDate
                                        }, function (err, res) {
                                            ca(err, res.obj);
                                        });
                                    },
                                    firstPrice: function (ca) {//昨天价格
                                        stockHistoryPriceDAO.getListPriceByTime({
                                            date: startDate,
                                            stockCodes: stockCodes
                                        }, function (err, result) {
                                            if (err) {
                                                console.log(err);
                                            } else {
                                                ca(null, result.obj);
                                            }
                                        });
                                    }
                                }, function (err, res) {
                                    cb(err, res);
                                });
                            }

                        },
                        jdInfos: function (cb) {
                            startDate = timeUtil.getFirstDayOfQuarter();
                            endDate = day.getFullYear() + "-" + (day.getMonth() + 1) + "-" + (day.getDate() + 1);
                            if (stockCodes.length == 0) {
                                cb(null, []);
                            } else {
                                async.parallel({
                                    startDeals: function (ca) {//季度前量
                                        stockDealDAO.getAllInDate({
                                            stockChannelIds: stockGroup && stockGroup.stockChannelIds || [],
                                            endDate: startDate
                                        }, function (err, res) {
                                            ca(err, res.obj);
                                        });
                                    },
                                    endDeals: function (ca) {//季度后量
                                        stockDealDAO.getAllInDate({
                                            stockChannelIds: stockGroup && stockGroup.stockChannelIds || [],
                                            startDate: startDate,
                                            endDate: endDate
                                        }, function (err, res) {
                                            ca(err, res.obj);
                                        });
                                    },
                                    firstPrice: function (ca) {//季度前一天价格
                                        stockHistoryPriceDAO.getListPriceByTime({
                                            date: startDate,
                                            stockCodes: stockCodes
                                        }, function (err, result) {
                                            if (err) {
                                                console.log(err);
                                            } else {
                                                ca(null, result.obj);
                                            }
                                        });
                                    }
                                }, function (err, res) {
                                    cb(err, res);
                                });
                            }

                        },
                        weekInfos: function (cb) {
                            startDate = timeUtil.getFirstDayOfWeek();
                            endDate = day.getFullYear() + "-" + (day.getMonth() + 1) + "-" + (day.getDate() + 1);
                            if (stockCodes.length == 0) {
                                cb(null, []);
                            } else {
                                async.parallel({
                                    startDeals: function (ca) {//一周前量
                                        stockDealDAO.getAllInDate({
                                            stockChannelIds: stockGroup && stockGroup.stockChannelIds || [],
                                            endDate: startDate
                                        }, function (err, res) {
                                            ca(err, res.obj);
                                        });
                                    },
                                    endDeals: function (ca) {//本周量
                                        stockDealDAO.getAllInDate({
                                            stockChannelIds: stockGroup && stockGroup.stockChannelIds || [],
                                            startDate: startDate,
                                            endDate: endDate
                                        }, function (err, res) {
                                            ca(err, res.obj);
                                        });
                                    },
                                    firstPrice: function (ca) {//本周前一天价格
                                        stockHistoryPriceDAO.getListPriceByTime({
                                            date: startDate,
                                            stockCodes: stockCodes
                                        }, function (err, result) {
                                            if (err) {
                                                console.log(err);
                                            } else {
                                                ca(null, result.obj);
                                            }
                                        });
                                    }
                                }, function (err, res) {
                                    cb(err, res);
                                });
                            }

                        },
                        monthInfos: function (cb) {
                            startDate = timeUtil.getFirstDayOfMonth();
                            endDate = day.getFullYear() + "-" + (day.getMonth() + 1) + "-" + (day.getDate() + 1);
                            if (stockCodes.length == 0) {
                                cb(null, []);
                            } else {
                                async.parallel({
                                    startDeals: function (ca) {//月前量
                                        stockDealDAO.getAllInDate({
                                            stockChannelIds: stockGroup && stockGroup.stockChannelIds || [],
                                            endDate: startDate
                                        }, function (err, res) {
                                            ca(err, res.obj);
                                        });
                                    },
                                    endDeals: function (ca) {//本月量
                                        stockDealDAO.getAllInDate({
                                            stockChannelIds: stockGroup && stockGroup.stockChannelIds || [],
                                            startDate: startDate,
                                            endDate: endDate
                                        }, function (err, res) {
                                            ca(err, res.obj);
                                        });
                                    },
                                    firstPrice: function (ca) {//本月前一天价格
                                        stockHistoryPriceDAO.getListPriceByTime({
                                            date: startDate,
                                            stockCodes: stockCodes
                                        }, function (err, result) {
                                            if (err) {
                                                console.log(err);
                                            } else {
                                                ca(null, result.obj);
                                            }
                                        });
                                    }
                                }, function (err, res) {
                                    cb(err, res);
                                });
                            }
                        },
                    }, function (err, result) {
                        var nums = [];
                    for (stockChannel of result.ljInfos) {
                        nums.push(stockChannel.positionNum)
                    }
                    let realPrices = 0;
                    async.parallel({
                        ljListRalt: function (cb) {
                            let ljPrices = 0;

                            let i = 0;
                            for (stockChannel of result.ljInfos) {
                                ljPrices += (stockChannel.cost || 0) * stockChannel.positionNum;
                                realPrices += (realPics[i] || 0) * stockChannel.positionNum;
                                i++;
                            }

                            cb(err, stockUtil.calcRate(realPrices, ljPrices));
                        },
                        yearListRalt: function (cb) {
                            that.countRate(result.yearInfos, stockGroup, cb);
                        },
                        dayListRalt: function (cb) {
                            that.countRate(result.dayInfos, stockGroup, cb);
                        },
                        jdListRalt: function (cb) {
                            that.countRate(result.jdInfos, stockGroup, cb);
                        },
                        weekListRalt: function (cb) {
                            that.countRate(result.weekInfos, stockGroup, cb);
                        },
                        monthListRalt: function (cb) {
                            that.countRate(result.monthInfos, stockGroup, cb);
                        },
                        stockPosition: function (cb) {
                            stockPositionDAO.findByGroupId({stockGroupId: stockGroup.rowId}, function (err, result) {
                                if (err) {
                                    cb(err, null);
                                } else {
                                    cb(err, result.obj);
                                }
                            });
                        }
                        }, function (err, res) {
                            stockGroup.stockPosition = res.stockPosition;
                            stockGroup.ljRate = res.ljListRalt;
                            stockGroup.yearRate = res.yearListRalt;
                            stockGroup.dayRate = res.dayListRalt;
                            stockGroup.jdRate = res.jdListRalt;
                            stockGroup.weekRate = res.weekListRalt;
                            stockGroup.monthRate = res.monthListRalt;
                            done(null, stockGroup)
                        })

                    }
                )

            }
        ], function (error, result) {
            if (error) {
                console.log(error);
                next({code: 404, message: '股票分组查询出错'})
            } else {
                next({code: 200, result});
            }
        });

    },
    countRate: function (result, stockGroup, cb) {
        let oldPrice = 0;
        let realPrices = 0;
        if (result.length == 0 || result.startDeals.length == 0) {//开始前未买入
            if (result.length == 0 || result.endDeals.length == 0) {//开始后未买入
                cb(null, '0%');
            } else {//开始后买入
                for (item of result.endDeals) {
                    oldPrice += item.val;
                }
                for (stockChannel of stockGroup.stockChannelIds) {
                    realPrices += stockChannel.positionNum * stockChannel.stockId.realPrice;//现价*总量
                }
                cb(null, stockUtil.calcRate(realPrices, oldPrice));
            }
        } else {//开始前买入
            for (stockChannel of stockGroup.stockChannelIds) {
                //if( result.endDeals.length > 0){
                // var inStartDeals = 0;
                for (item of result.endDeals) {
                    if (stockChannel.stockId.stockCode.substring(0, stockChannel.stockId.stockCode.indexOf(".")) == item.stockCode) {
                        for (stockPrice of result.firstPrice) {
                            if (stockChannel.stockId.stockCode.substring(0, stockChannel.stockId.stockCode.indexOf(".")) == stockPrice.stockCode) {
                                //oldPrice += stockPrice.price * ((stockChannel.positionNum - item.nums)==0?item.nums:(stockChannel.positionNum - item.nums));
                                oldPrice += item.val;

                                console.log(1)
                            }
                        }
                    }
                }
                realPrices += stockChannel.positionNum * stockChannel.stockId.realPrice;//现价*总量
                for (item of result.startDeals) {
                    //inStartDeals++;
                    if (item.stockCode == stockChannel.stockId.stockCode.substring(0, stockChannel.stockId.stockCode.indexOf("."))) {
                        for (stockPrice of result.firstPrice) {
                            if (item.stockCode == stockPrice.stockCode) {

                                oldPrice += stockPrice.price * item.nums;
                                //realPrices += stockChannel.positionNum * stockChannel.stockId.realPrice;//现价*总量
                                console.log(1)
                            }
                        }
                    }
                }
            }
            cb(null, stockUtil.calcRate(realPrices, oldPrice));
        }
    },
    addChannels: function (req, res, next) {
        var params = req.query;
        if (params == null) {
            res.redirect('/error');
            return;
        }
        stockGroupDAO.addChannels(params, function (err, result) {
            next(err || result);
        });
    },
    //获取个人持仓详情
    getStockList: function (req, res, next) {
        var params = {};
        params.groupId = req.body.params.groupId || '';
        if (req.session.userinfo && req.session.userinfo.role == 0)
            params.createUid = req.session.uid;
        var that = this;
        async.waterfall([
            function (done) {
                stockChannelDAO.getByGroupId({stockGroupId: params.groupId}, function (err, list) {
                    done(err, list.obj);
                });
            },
            // function (stockChannelList, done) {
            //
            //     var stockChannelIds = [];
            //
            //     for (stockChannel of stockChannelList.obj) {
            //         stockChannelIds.push(stockChannel.rowId);
            //     }
            //     stockDealDAO.getByStockChannelIds({stockChannelIds: stockChannelIds}, function (err, list) {
            //         let i = 0;
            //         for (deal of list.obj) {
            //             deal.stockName = stockChannelList.obj[i].stockId.name;
            //             deal.stockCode = stockChannelList.obj[i].stockId.stockCode;
            //             deal.stockRowId = stockChannelList.obj[i].stockId.rowId;
            //             i++;
            //         }
            //         done(err, list && list.obj || null);
            //
            //     });
            //
            // },

            function (result, done) {
                async.map(result, function (item, callback) {
                    stockUtil.getRealtimePrice(item.stockId.stockCode, function (err, price) {
                        item.positionVal = Math.round(item.positionNum * price);
                        item.realPic = price;
                        item.realRate = that.countRalt(item.cost, price);
                        callback(err, item);
                    })
                }, function (err, result) {
                    done(err, result);
                });

            },
        ], function (error, result) {
            if (error) {
                console.log(error);
                next({code: 404, message: '查询持仓详情错误'})
            } else {
                console.log(result);
                next(error, result);
            }
        });
    },
    deleteByIds: function (req, res, next) {
        var rowIds = req.body.rowIds || [];
        if (rowIds.length > 0) {
            stockGroupDAO.deleteByIds(rowIds, function (err, result) {
                next(err, result);
            });
        } else {
            next();
        }
    }
}